package unilearn.da;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.*;

import org.apache.commons.fileupload.util.Streams;

import unilearn.domain.DataFile;

/**
 * @author James Owen, 5655595
 * @author Yin Zhang, 5393558
 * @author Ben Morrall, 4158768
 * @version 0.1, 13 April 2008, initial creation.
 * @version 0.2,
 * @version 0.3, 14 May 2008, Refactor Code, blm
 */
public class DAFile extends DABase
{

	public static DataFile getByFileID(long fileID) throws SQLException, IOException,
		NamingException
	{
		DataFile file = null;
		PreparedStatement ps = null;

		try
		{
			Connection conn = getConn();

			ps = conn.prepareStatement("SELECT * FROM data_file WHERE file_id = ?");
			ps.setLong(1, fileID);
			ResultSet rs = ps.executeQuery();

			if (rs.next())
			{
				file = new DataFile();
				file.setFileID(rs.getLong("file_id"));
				file.setFileName(rs.getString("file_name"));
				file.setFileSize(rs.getLong("file_size"));
				file.setFileType(rs.getString("file_type"));

				Blob fileBlob = rs.getBlob("file_data");
				if (fileBlob != null)
				{
					InputStream inStream = fileBlob.getBinaryStream();
					File tempFile = File.createTempFile("download", ".tmp");
					FileOutputStream outStream = new FileOutputStream(tempFile);
					Streams.copy(inStream, outStream, true);
					file.setFile(tempFile);
				}
			}
		}
		finally
		{
			if (ps != null) ps.close();
		}

		return file;
	}

	public static long insertFile(DataFile file) throws SQLException, IOException
	{
		long newId = -1;
		PreparedStatement ps = null;

		try
		{
			Connection conn = getConn();

			ps = conn.prepareStatement(
					"INSERT INTO data_file(file_name,file_type,file_size,file_data) values(?,?,?,?)",
					Statement.RETURN_GENERATED_KEYS);

			ps.setString(1, file.getFileName());
			ps.setString(2, file.getFileType());
			ps.setLong(3, file.getFileSize());

			FileInputStream fileInStream = new FileInputStream(file.getFile());
			ps.setBinaryStream(4, fileInStream, (int) file.getFileSize());
			ps.execute();

			ResultSet results = ps.getGeneratedKeys();
			if (results.next())
			{
				newId = results.getLong(1);
				file.setFileID(newId);
			}
		}
		finally
		{
			if (ps != null) ps.close();
		}

		return newId;
	}

	/**
	 * Prevent Instances of DAFile
	 */
	private DAFile()
	{
	}

}
